package com.dingreading.cloud.admin.controller;

import com.dingreading.cloud.admin.dto.ComboGoodsTypeDto;
import com.dingreading.cloud.admin.dto.GoodsAndTypeDto;
import com.dingreading.cloud.admin.dto.GoodsTypeComboDto;
import com.dingreading.cloud.admin.dto.GoodsTypeNumsDto;
import com.dingreading.cloud.admin.entity.Goods;
import com.dingreading.cloud.admin.entity.GoodsSuppliers;
import com.dingreading.cloud.admin.entity.GoodsType;
import com.dingreading.cloud.admin.entity.GoodsTypeCombo;
import com.dingreading.cloud.admin.mapper.GoodsTypeMapper;
import com.dingreading.cloud.admin.service.*;
import com.dingreading.cloud.admin.util.bean.GoodsV3Util;
import com.dingreading.cloud.admin.util.bean.OrderFormV3Util;
import com.dingreading.cloud.admin.util.redis.RedisService;
import com.dingreading.cloud.common.base.R;
import com.dingreading.cloud.common.util.*;
import com.mybatisflex.core.paginate.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = "/system/goodsType/v3")
@Api(tags = "总部-商品规格管理V3")
public class GoodsTypeControllerV3 {

    @Resource
    protected GoodsService goodsService;
    @Resource
    protected GoodsTypeService goodsTypeService;
    @Resource
    protected GoodsTypeComboService goodsTypeComboService;
    @Resource
    protected GoodsSuppliersService goodsSuppliersService;
    @Resource
    protected ShopCartService shopCartService;
    @Resource
    protected WhStockOutGoodsService stockOutGoodsService;
    @Resource
    protected WhStockInService stockInService;
    @Resource
    protected GoodsTypeMapper goodsTypeMapper;
    @Resource
    protected RedisService redisService;


    @ApiOperation(value = "供应商获取商品规格列表")
    @PostMapping(value = "/getGoodsTypes", produces = "application/json; charset=UTF-8")
    public R<Object> getGoodsTypes(
            @ApiParam(value = "分页公共类") PageUtil pageUtil,
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "商品名/商品规格名") @RequestParam(value = "name", required = false) String name,
            @ApiParam(value = "状态 1.启用 0.禁用") @RequestParam(value = "enabled", required = false) Integer enabled,
            @ApiParam(value = "供应商id") @RequestParam(value = "suppliersId", required = false) Long suppliersId
    ) {
        PageDto<GoodsAndTypeDto> page = goodsTypeService.goodsTypePageList(pageUtil, name, 0, 1);

        List<GoodsAndTypeDto> results = page.getList();
        if (CollectionUtils.isNotEmpty(results)) {
            List<Long> goodsTypeIds = results.stream().map(GoodsAndTypeDto::getGoodsTypeId).collect(Collectors.toList());
            List<GoodsSuppliers> goodsSuppliers = goodsSuppliersService.getBySupplierIdAndGoodsTypeIdIn(suppliersId, goodsTypeIds);
            Map<Long, GoodsSuppliers> map = new HashMap<>();
            if (CollectionUtils.isNotEmpty(goodsSuppliers)) {
                map = goodsSuppliers.stream().collect(Collectors.toMap(GoodsSuppliers::getGoodsTypeId, Function.identity()));
            }
            for (GoodsAndTypeDto typeDto : results) {
                if (null != map.get(typeDto.getGoodsTypeId())) {
                    typeDto.setStatus(1);
                } else {
                    typeDto.setStatus(0);
                }
            }
        }

        return R.ok(page);
    }


    @ApiOperation(value = "组合商品获取商品规格列表")
    @PostMapping(value = "/getGoodsTypesToCombo", produces = "application/json; charset=UTF-8")
    public R<Object> getGoodsTypesToCombo(
            @ApiParam(value = "分页公共类") PageUtil pageUtil,
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "商品id") @RequestParam(value = "goodsId", required = false) Long goodsId,
            @ApiParam(value = "商品名/商品规格名") @RequestParam(value = "name", required = false) String name
    ) {
        PageDto<GoodsAndTypeDto> page = goodsTypeService.goodsTypePageList(pageUtil, name, 0, 1);
        List<GoodsAndTypeDto> list = page.getList();
        if (CollectionUtils.isNotEmpty(list)) {
            List<Long> goodsTypeIds = list.stream().map(GoodsAndTypeDto::getGoodsTypeId).collect(Collectors.toList());

            // 获取库存数量
            Map<Long, Integer> stockNumMap = stockInService.getStockNumMap(goodsTypeIds);
            // 根据购买记录和出库记录获取商品规格的待出库数量集合
            Map<Long, Integer> waitSendNumMap = shopCartService.getWaitSendNum(goodsTypeIds);

            for (GoodsAndTypeDto dto : list) {
                // 库存数-待发货数
                Long typeId = dto.getGoodsTypeId();
                int stockNum = NepUtil.nullToZero(stockNumMap.get(typeId));
                int waitSendNum = NepUtil.nullToZero(waitSendNumMap.get(typeId));
                if (stockNum > 0)
                    stockNum -= waitSendNum;
                dto.setStockNum(stockNum);
            }
        }
        return R.ok(page);
    }


    @ApiOperation(value = "判断删除商品分类")
    @PostMapping(value = "/judgeDrop", produces = "application/json; charset=UTF-8")
    public R<Object> judgeDrop(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "id") @RequestParam(value = "id") Long id
    ) {
        GoodsType data = goodsTypeService.getById(id);
        if (null == data)
            return R.fail("获取失败");

        // 判断商品规格是否被使用
        String msg = GoodsV3Util.judgeUseGoodsType(id);
        if (StringUtils.isNotBlank(msg))
            return R.fail(msg);

        return R.ok();
    }


    @ApiOperation(value = "获取商品库存数、加权价、已售数、统计")
    @PostMapping(value = "/getGoodsDetails", produces = "application/json; charset=UTF-8")
    public R<Object> getGoodsDetails(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "分页公共类") PageUtil pageUtil,
            @ApiParam(value = "商品名") @RequestParam(value = "keyword", required = false) String keyword,
            @ApiParam(value = "门店类型 1.自营门店、2.总部、3.加盟店") @RequestParam(value = "storeType", required = false) Integer storeType,
            @ApiParam(value = "库存数量排序 1.降序 2.升序") @RequestParam(value = "orderByType", required = false) Integer orderByType
    ) {
        Page<GoodsTypeNumsDto> page = goodsTypeService.goodsStockPage(pageUtil, keyword, orderByType);

        List<GoodsTypeNumsDto> list = page.getRecords();
        if (CollectionUtils.isNotEmpty(list)) {
            Set<Long> typeIds = new HashSet<>();
            Set<Long> comboMainTypeIds = new HashSet<>();
            for (GoodsTypeNumsDto dto : list) {
                if (dto.getComboType().equals(0))
                    typeIds.add(dto.getGoodsTypeId());
                else
                    comboMainTypeIds.add(dto.getGoodsTypeId());
            }

            // 查询组合商品的子商品信息
            Map<Long, List<GoodsTypeComboDto>> comboMap = new HashMap<>();
            if (CollectionUtils.isNotEmpty(comboMainTypeIds)) {
                List<GoodsTypeComboDto> goodsTypeComboList = goodsTypeComboService.dtoListByMainGoodsTypeIds(new ArrayList<>(comboMainTypeIds));
                if (CollectionUtils.isNotEmpty(goodsTypeComboList)) {
                    comboMap = goodsTypeComboList.stream().collect(Collectors.groupingBy(GoodsTypeComboDto::getMainGoodsTypeId));

                    // 获取组合商品内的子商品规格id
                    List<Long> childGoodsTypeIds = goodsTypeComboList.stream().map(GoodsTypeComboDto::getGoodsTypeId).collect(Collectors.toList());
                    typeIds.addAll(childGoodsTypeIds);
                }
            }

            List<Long> goodsTypeIds = new ArrayList<>(typeIds);

            // 商品规格的库存数量
            Map<Long, Integer> stockNumMap = stockInService.getStockNumMap(goodsTypeIds);
            // 商品规格的待发货数量
            Map<Long, Integer> waitSendNumMap = shopCartService.getWaitSendNum(goodsTypeIds);
            // 获取商品的采购数量
            Map<Long, Integer> inNumMap = stockInService.getInNum(goodsTypeIds);
            // 获取普通商品的出库数量
            Map<Long, Integer> sendNumMap = stockOutGoodsService.getSendNum(goodsTypeIds);

            // 按门店类型获取普通商品和组合商品的已售数量
            goodsTypeIds.addAll(comboMainTypeIds);
            Map<Long, Integer> soldNumMap = new HashMap<>();
            if (storeType != null) {
                soldNumMap = shopCartService.getSoldNum(goodsTypeIds, storeType);
            } else {
                soldNumMap = shopCartService.getSoldNum(goodsTypeIds, null);
            }

            for (GoodsTypeNumsDto dto : list) {
                Long goodsTypeId = dto.getGoodsTypeId();

                dto.setSoldNumCnt(NepUtil.nullToZero(soldNumMap.get(goodsTypeId)));
                if (dto.getComboType().equals(0)) {
                    Integer sendNum = NepUtil.nullToZero(sendNumMap.get(goodsTypeId));
                    Integer intNum = NepUtil.nullToZero(inNumMap.get(goodsTypeId));
                    Integer waitSendNum = waitSendNumMap.get(goodsTypeId);
                    dto.setInNumCnt(intNum);
                    dto.setSendNumCnt(sendNum);
                    dto.setWaitNumCnt(waitSendNum);

                    int stockNum = OrderFormV3Util.getGoodsTypeNum(stockNumMap.get(goodsTypeId), waitSendNum);
                    dto.setStockNumCnt(stockNum);
                } else {
                    dto.setInNumCnt(null);
                    dto.setWetAcePrice(null);
                    dto.setStockPrice(null);
                    // 组合商品
                    List<GoodsTypeComboDto> comboDtoList = comboMap.get(goodsTypeId);
                    // 获取组合商品的最低可售数量和总重量
                    ComboGoodsTypeDto comboGoodsTypeDto = GoodsV3Util.getComboGoodsTypeDto(comboDtoList, stockNumMap, waitSendNumMap);
                    dto.setStockNumCnt(comboGoodsTypeDto.getSaleNum());
                    dto.setWeight(comboGoodsTypeDto.getWeight());
                }
            }
        }

        PageBeanDto dto = new PageBeanDto();
        dto.setList(list);
        dto.setTotal(page.getTotalRow());
        return R.ok(dto);
    }


    @ApiOperation(value = "获取库存预警的数量")
    @PostMapping(value = "/getGoodsWarningNum", produces = "application/json; charset=UTF-8")
    public R<Object> getGoodsWarningNum(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName
    ) {
        long num = goodsTypeService.getGoodsWarningNum();

        return R.ok(num);
    }


    @ApiOperation(value = "获取库存预警的商品")
    @PostMapping(value = "/goodsWarningList", produces = "application/json; charset=UTF-8")
    public R<Object> goodsWarningList(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "分页公共类") PageUtil pageUtil,
            @ApiParam(value = "商品名称") @RequestParam(value = "keyword", required = false) String keyword
    ) {
        Page<GoodsTypeNumsDto> page = goodsTypeService.goodsWarnPage(pageUtil, keyword);

        List<GoodsTypeNumsDto> list = page.getRecords();

        if (CollectionUtils.isNotEmpty(list)) {
            List<Long> goodsTypeIds = list.stream().map(GoodsTypeNumsDto::getGoodsTypeId).collect(Collectors.toList());

            // 获取商品的采购数量
            Map<Long, Integer> inNumMap = stockInService.getInNum(goodsTypeIds);

            // 获取商品的已售数量
            Map<Long, Integer> soldNumMap = shopCartService.getSoldNum(goodsTypeIds, null);

            // 获取商品的已出库数量
            Map<Long, Integer> sendNumMap = stockOutGoodsService.getSendNum(goodsTypeIds);

            // 根据购买记录和出库记录获取商品规格的待出库数量
            Map<Long, Integer> waitSendNumMap = shopCartService.getWaitSendNum(goodsTypeIds);

            for (GoodsTypeNumsDto dto : list) {
                Long goodsTypeId = dto.getGoodsTypeId();
                Integer soldNum = NepUtil.nullToZero(soldNumMap.get(goodsTypeId));
                Integer sendNum = NepUtil.nullToZero(sendNumMap.get(goodsTypeId));
                Integer intNum = NepUtil.nullToZero(inNumMap.get(goodsTypeId));
                Integer waitSendNum = NepUtil.nullToZero(waitSendNumMap.get(goodsTypeId));
                dto.setSoldNumCnt(soldNum);
                dto.setSendNumCnt(sendNum);
                dto.setInNumCnt(intNum);
                dto.setWaitNumCnt(waitSendNum);
            }
        }

        PageBeanDto dto = new PageBeanDto();
        dto.setList(list);
        dto.setTotal(page.getTotalRow());
        return R.ok(dto);
    }


    @Transactional(rollbackFor = DescribeException.class)
    @ApiOperation(value = "添加/编辑正常或组合商品规格")
    @PostMapping(value = "/editBean2", produces = "application/json; charset=UTF-8")
    public R<Object> editBean2(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "关联的商品id") @RequestParam(value = "goodsId") Long goodsId,
            @ApiParam(value = "商品规格id") @RequestParam(value = "id", required = false) Long id,
            @ApiParam(value = "商品类型 0.正常商品 1.组合商品") @RequestParam(value = "comboType") Integer comboType,
            @ApiParam(value = "商品规格名") @RequestParam(value = "name") String name,
            @ApiParam(value = "商品售价") @RequestParam(value = "price") Double price,
            @ApiParam(value = "商品单位") @RequestParam(value = "unit") String unit,
            @ApiParam(value = "封面图") @RequestParam(value = "img") String img,
            @ApiParam(value = "重量/克") @RequestParam(value = "weight", required = false) Double weight,
            @ApiParam(value = "库存预警数量") @RequestParam(value = "warnNum", required = false) Integer warnNum,
            @ApiParam(value = "上架状态 1.上架 0.下架") @RequestParam(value = "enabled") Integer enabled,
            @ApiParam(value = "出库方式 1.自营仓库 2.线上发货 3.第三方仓库") @RequestParam(value = "stockOutMethod", required = false) Integer stockOutMethod,
            @ApiParam(value = "运营类型") @RequestParam(value = "operationType") String operationType,
            @ApiParam(value = "合作类型") @RequestParam(value = "cooperationType") String cooperationType,
            @ApiParam(value = "科目类型") @RequestParam(value = "subjectType", required = false) String subjectType,
            @ApiParam(value = "商城折扣状态 1.启用 0.禁用") @RequestParam(value = "discountStatus", required = false) Integer discountStatus,
            @ApiParam(value = "套裝能否包邮 0.不包邮 1.包邮") @RequestParam(value = "freeDeliveryStatus", required = false) Integer freeDeliveryStatus,
            @ApiParam(value = "组合商品集合 [{id:0,goodsId:0,goodsTypeId:0,num:0}]}]") @RequestBody(required = false) List<GoodsTypeCombo> comboList
    ) throws Exception {
        if (null == comboType)
            return R.fail("请选择商品类型");
        if (StringUtils.isBlank(name))
            return R.fail("请填写商品规格的名称");
        if (StringUtils.isBlank(img))
            return R.fail("请添加商品规格的图片");
        if (StringUtils.isBlank(unit))
            return R.fail("请选择商品规格的单位");
        if (StringUtils.isBlank(cooperationType))
            return R.fail("请选择合作类型");
        if (StringUtils.isBlank(operationType))
            return R.fail("请选择运营类型");
        if (null == price || price <= 0)
            return R.fail("请填写正确的商品规格的价格");
        if (comboType.equals(0)) {
            if (weight == null || weight < 0)
                return R.fail("请填写商品规格的重量（克）");
            if (stockOutMethod == null)
                return R.fail("请选择出库方式");
        }
        if (null == enabled)
            return R.fail("请选择启用状态");

        Goods goods = goodsService.getDataById(goodsId);
        if (goods == null)
            return R.fail("商品不存在");
        if (goods.getFreeDeliveryId() == null || goods.getFreeDeliveryId() <= 0)
            return R.fail("主商品未设置包邮模板");

        Map<Long, Goods> goodsMap = new HashMap<>();
        Map<Long, GoodsType> goodsTypeMap = new HashMap<>();
        if (comboType.equals(1)) {
            // 只在新增时可编辑子商品信息
            if (CollectionUtils.isEmpty(comboList))
                return R.fail("组合商品的子商品未选择");

            if (comboList.size() < 1 || comboList.size() > 50)
                return R.fail("组合商品内的商品数量不能少于1个或大于50个");

            Set<Long> goodsIds = new HashSet<>();
            Set<Long> goodsTypeIds = new HashSet<>();
            for (GoodsTypeCombo typeCombo : comboList) {
                if (typeCombo.getGoodsId() == null)
                    return R.fail("子商品的商品id未传");
                if (typeCombo.getGoodsTypeId() == null)
                    return R.fail("子商品的商品规格id未传");
                if (typeCombo.getNum() == null || typeCombo.getNum() <= 0)
                    return R.fail("子商品的可售数量错误");
                goodsIds.add(typeCombo.getGoodsId());
                goodsTypeIds.add(typeCombo.getGoodsTypeId());
            }

            List<Goods> goodsList = goodsService.listByIds(goodsIds);
            if (CollectionUtils.isEmpty(goodsList) || goodsIds.size() != goodsList.size())
                return R.fail("子商品关联的商品查询失败");
            List<GoodsType> goodsTypeList = goodsTypeService.listByIds(goodsTypeIds);
            if (CollectionUtils.isEmpty(goodsTypeList) || goodsTypeIds.size() != goodsTypeList.size())
                return R.fail("子商品关联的商品规格查询失败");

            goodsMap = goodsList.stream().collect(Collectors.toMap(Goods::getId, Function.identity()));
            goodsTypeMap = goodsTypeList.stream().collect(Collectors.toMap(GoodsType::getId, Function.identity()));
        }

        GoodsType goodsType = null;
        boolean updatePrice = false;
        if (id == null || id <= 0) {
            // 获取最大的序号
            int maxOrderNum = goodsTypeService.getMaxShowOrder(goodsId, comboType);

            goodsType = new GoodsType();
            goodsType.setOrderNum(maxOrderNum + 1);
            goodsType.setName(name);
            goodsType.setGoodsId(goodsId);
            goodsType.setComboType(comboType);
            goodsType.setAddStaffUid(headStaffUid);
            goodsType.setAddStaffName(headStaffName);
        } else {
            goodsType = goodsTypeService.getById(id);
            if (goodsType == null)
                return R.fail("商品规格获取失败");
            // 如果价格不一样，则更新
            if (!price.equals(goodsType.getPrice()))
                updatePrice = true;
        }
        String exImg = goodsType.getImg();
        goodsType.setUnit(unit);
        goodsType.setPrice(price);
        if (comboType.equals(0)) {
            goodsType.setWeight(weight);
            goodsType.setWarnNum(warnNum);
        } else {
            goodsType.setFreeDeliveryStatus(freeDeliveryStatus);
        }
        goodsType.setImg(img);
        goodsType.setCooperationType(cooperationType);
        goodsType.setOperationType(operationType);
        goodsType.setSubjectType(NepUtil.nullToZero(subjectType));
        goodsType.setDiscountStatus(discountStatus);
        goodsType.setStockOutMethod(stockOutMethod);
        goodsType.setEnabled(enabled);
        goodsType.setLastStaffUid(headStaffUid);
        goodsType.setLastStaffName(headStaffName);
        goodsTypeMapper.insertOrUpdate(goodsType, false);

        Long goodsTypeId = goodsType.getId();
        if (goodsTypeId == null || goodsTypeId <= 0)
            return R.fail("商品规格创建失败");

        if (comboType.equals(1) && CollectionUtils.isNotEmpty(comboList)) {
            if (id == null || id <= 0) {
                for (int i = 0; i < comboList.size(); i++) {
                    GoodsTypeCombo typeCombo = comboList.get(i);
                    Goods cGoods = goodsMap.get(typeCombo.getGoodsId());
                    GoodsType cGoodsType = goodsTypeMap.get(typeCombo.getGoodsTypeId());
                    if (cGoods == null || cGoodsType == null)
                        throw new DescribeException("子商品关联的商品或规格查询失败");
                    if (typeCombo.getMainGoodsTypeId() == null)
                        typeCombo.setMainGoodsTypeId(goodsTypeId);
                    typeCombo.setMainGoodsId(goodsId);
                    typeCombo.setEnabled(1);
                }
                goodsTypeComboService.saveOrUpdateBatch(comboList);
            }
        }

        // 修改价格后，同步更新购物车的商品价格
        if (updatePrice)
            shopCartService.updateUnitPrice(id, price);

        // 删除阿里云上存储的图片
        if (StringUtils.isNotBlank(exImg) && !img.equals(exImg))
            GoodsV3Util.deleteOssFiles(Collections.singletonList(exImg));

        // 清除商城商品种类
        redisService.setNullLike(RedisParam.MALL_CATEGORY);
        return R.ok(goodsType.getId());
    }


    @ApiOperation(value = "获取出商品规格详情")
    @PostMapping(value = "/getBean", produces = "application/json; charset=UTF-8")
    public R<Object> getBean(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "商品规格id") @RequestParam(value = "id") Long id
    ) {
        GoodsType data = goodsTypeService.getById(id);
        if (data == null)
            return R.fail("商品规格获取失败");
        if (data.getComboType().equals(1)) {
            List<GoodsTypeCombo> comboList = goodsTypeComboService.listByMainGoodsTypeIds(Collections.singletonList(data.getId()));
            data.setComboList(comboList);
        }
        return R.ok(data);
    }


    @ApiOperation(value = "修改商品分类启用状态")
    @PostMapping(value = "/updateEnabled", produces = "application/json; charset=UTF-8")
    public R<Object> updateTypeEnabled(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "id") @RequestParam(value = "id") Long id,
            @ApiParam(value = "启用状态 0.禁用 1.启用") @RequestParam(value = "enabled") Integer enabled
    ) {
        GoodsType goodsType = goodsTypeService.getById(id);
        if (goodsType == null)
            return R.fail("商品规格获取失败");

        boolean b = goodsTypeService.updateEnabled(id, enabled, headStaffUid, headStaffName);
        if (!b)
            return R.fail("更新失败");

        // 商品下架，取消购物车记录
        if (enabled.equals(0))
            shopCartService.cancelShopCartByGoodsTypeId(goodsType.getComboType(), id);

        // 清除商城商品种类
        redisService.setNullLike(RedisParam.MALL_CATEGORY);
        return R.ok();
    }


    @ApiOperation(value = "删除商品规格")
    @PostMapping(value = "/dropBean", produces = "application/json; charset=UTF-8")
    public R<Object> dropBean(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "商品id") @RequestParam(value = "goodsId") Long goodsId,
            @ApiParam(value = "商品规格id") @RequestParam(value = "id") Long id
    ) {
        GoodsType goodsType = goodsTypeService.getById(id);
        if (goodsType == null)
            return R.fail("商品规格获取失败");

        // 判断商品规格是否被使用
        String msg = GoodsV3Util.judgeUseGoodsType(id);
        if (StringUtils.isNotBlank(msg))
            return R.fail(msg);

        // / 删除商品规格
        int l = goodsTypeService.deleteByGoodsIdAndId(goodsId, id);
        if (l <= 0)
            return R.failDel();

        // / 删除商品组合
        if (goodsType.getComboType().equals(1))
            goodsTypeComboService.deleteByMainGoodsIdAndMainGoodsTypeId(goodsId, id);

        // 删除阿里云上存储的文件
        String goodsTypeImg = goodsType.getImg();
        if (StringUtils.isNotBlank(goodsTypeImg)) {
            GoodsV3Util.deleteOssFiles(Collections.singletonList(goodsTypeImg));
        }

        // 清除商城商品种类
        redisService.setNullLike(RedisParam.MALL_CATEGORY);
        return R.ok();
    }


    @ApiOperation(value = "正常商品规格上移/下移")
    @PostMapping(value = "/upOrDown", produces = "application/json; charset=UTF-8")
    public R<Object> upOrDown(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "id") @RequestParam(value = "id") Long id,
            @ApiParam(value = "类型 1.上移 2.下移") @RequestParam(value = "type") Integer type
    ) {
        GoodsType data = goodsTypeService.getById(id);
        if (data == null) return R.fail("获取失败");
        if (type.equals(1)) {
            // 上移
            GoodsType preData = goodsTypeService.getLtOrderNum(data.getGoodsId(), data.getComboType(), data.getOrderNum());
            if (preData == null) return R.fail("已在最前");
            // 和前一条记录的序号互换
            Integer prevOrderNum = preData.getOrderNum();
            Integer curOrderNum = data.getOrderNum();
            // 序号互换
            goodsTypeService.updateOrderNum(preData.getId(), curOrderNum);
            goodsTypeService.updateOrderNum(data.getId(), prevOrderNum);
        } else if (type.equals(2)) {
            // 下移
            GoodsType backData = goodsTypeService.getGtOrderNum(data.getGoodsId(), data.getComboType(), data.getOrderNum());
            if (backData == null) return R.fail("已在最后");
            // 和后一条记录的序号互换
            Integer backOrderNum = backData.getOrderNum();
            Integer curOrderNum = data.getOrderNum();
            // 序号互换
            goodsTypeService.updateOrderNum(backData.getId(), curOrderNum);
            goodsTypeService.updateOrderNum(data.getId(), backOrderNum);
        } else {
            return R.fail("类型错误");
        }
        return R.ok();
    }

    @ApiOperation(value = "复制套装商品")
    @PostMapping(value = "/copyGoodTypeCombo", produces = "application/json; charset=UTF-8")
    public R<Object> copyGoodTypeCombo(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "商品id") @RequestParam(value = "goodsId") Long goodsId,
            @ApiParam(value = "商品规格id") @RequestParam(value = "goodsTypeId") Long goodsTypeId,
            @ApiParam(value = "商品规格名称") @RequestParam(value = "goodsTypeName") String goodsTypeName
    ) {
        Goods goods = goodsService.getById(goodsId);
        if (goods == null)
            return R.fail("获取商品失败");

        GoodsType goodsType = goodsTypeService.getByGoodsIdAndGoodsTypeId(goodsId, goodsTypeId);
        if (goodsType == null)
            return R.fail("获取商品规格失败");

        List<GoodsTypeCombo> goodsTypeComboList = goodsTypeComboService.listByMainGoodsIdAndMainGoodsTypeId(goodsId, goodsTypeId);
        if (CollectionUtils.isEmpty(goodsTypeComboList))
            return R.fail("商品套装内的商品获取失败");

        goodsType.setId(null);
        goodsType.setName(goodsTypeName);
        goodsTypeService.save(goodsType);

        Long newGoodsTypeId = goodsType.getId();
        if (newGoodsTypeId == null || newGoodsTypeId <= 0)
            return R.fail("商品套装新增失败");

        for (GoodsTypeCombo goodsTypeCombo : goodsTypeComboList) {
            goodsTypeCombo.setId(null);
            goodsTypeCombo.setMainGoodsTypeId(newGoodsTypeId);
        }
        goodsTypeComboService.saveBatch(goodsTypeComboList);

        return R.ok();
    }


    @ApiOperation(value = "修改商城折扣的启用状态")
    @PostMapping(value = "/updateDiscountStatus", produces = "application/json; charset=UTF-8")
    public R<Object> updateDiscountStatus(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "id") @RequestParam(value = "id") Long id,
            @ApiParam(value = "启用状态 0.禁用 1.启用") @RequestParam(value = "discountStatus") Integer discountStatus
    ) {
        GoodsType goodsType = goodsTypeService.getById(id);
        if (goodsType == null)
            return R.fail("商品规格获取失败");

        boolean b = goodsTypeService.updateDiscountStatus(id, discountStatus, headStaffUid, headStaffName);
        if (!b)
            return R.fail("更新失败");

        return R.ok();
    }


}
